package org.dizem.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * User: dizem@126.com
 * Time: 11-7-1 下午12:25
 */
public final class XmlReader {
	private Document document;
	private NodeList rootList;

	public XmlReader(String filename) {
		try {
			DocumentBuilder bf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			document = bf.parse(filename);
			rootList = document.getChildNodes().item(0).getChildNodes();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public List<Node> getNodeList(String name) {
		List<Node> list = new ArrayList<Node>();
		for (int i = 0; i < rootList.getLength(); ++i) {
			if (rootList.item(i).getNodeName().equals(name)) {
				NodeList nodeList = rootList.item(i).getChildNodes();
				for (int j = 0; j < nodeList.getLength(); ++j) {
					if (nodeList.item(j).getNodeType() == Node.ELEMENT_NODE)
						list.add(nodeList.item(j));
				}
			}
		}
		return list;
	}

	public static String getChildNodeValue(Node node, String name) {
		NodeList nodeList = node.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); ++i) {
			if (nodeList.item(i).getNodeName().equals(name)) {
				return nodeList.item(i).getChildNodes().item(0).getNodeValue();
			}
		}
		return null;
	}

	public static Node getChildNode(Node node, String name) {
		NodeList nodeList = node.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); ++i) {
			if (nodeList.item(i).getNodeName().equals(name)) {
				return nodeList.item(i);
			}
		}
		return null;
	}

	public static String getAttribute(Node node, String name) {
		return node.getAttributes().getNamedItem(name).getNodeValue();
	}
}
